package com.example.administrator.energyida.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.energyida.R;
import com.example.administrator.energyida.beans.CompanyBean;
import com.example.administrator.energyida.beans.FactoryBean;
import com.example.administrator.energyida.beans.WorkshopBean;
import com.example.administrator.energyida.util.OceanUtil;
import com.google.gson.Gson;
import com.jaeger.library.StatusBarUtil;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class LinkManActivity extends Activity {

    private Button buttonFactoryChar;
    private Button buttonFarmChar;
    private ListView listViewLinkMan;
    private TextView textViewBack;

    private SimpleAdapter simpleAdapter;
    private ArrayList<HashMap<String, Object>> listFactoryChar = new ArrayList<>();
    private ArrayList<HashMap<String, Object>> listFarmChar = new ArrayList<>();
    private boolean leftIsClick;
    private boolean rightIsClick;

    private String email;
    private Handler handler;
    private String getFPhoneResponse;
    private String getWPhoneResponse;

    private List<FactoryBean.ContentBean> listFactoryBeans;
    private List<List<WorkshopBean.ContentBean>> listWorkshopBeans = new ArrayList<>();

    private QMUITipDialog qmuiTipDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_linkman);

        // 设置状态栏的颜色
        StatusBarUtil.setColor(this, Color.parseColor("#10cafd"), 50);

        initView();
        initHandler();

        buttonFactoryChar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (leftIsClick) {
                    return;
                }
                buttonFactoryChar.setBackgroundResource(R.color.colorAccent);
                buttonFarmChar.setBackgroundResource(R.color.color_bg_grey);
                buttonFarmChar.setTextColor(Color.parseColor("#000000"));
                buttonFactoryChar.setTextColor(Color.parseColor("#ffffff"));

                initAdapter(listFactoryChar);
                simpleAdapter.notifyDataSetChanged();
                rightIsClick = false;
                leftIsClick = true;
            }
        });

        buttonFarmChar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (rightIsClick) {
                    return;
                }
                buttonFactoryChar.setBackgroundResource(R.color.color_bg_grey);
                buttonFarmChar.setBackgroundResource(R.color.colorAccent);
                buttonFarmChar.setTextColor(Color.parseColor("#ffffff"));
                buttonFactoryChar.setTextColor(Color.parseColor("#000000"));

                initAdapter(listFarmChar);
                simpleAdapter.notifyDataSetChanged();
                rightIsClick = true;
                leftIsClick = false;
            }
        });

        //点击跳转到拨号界面
        listViewLinkMan.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                TextView phoneNumber = view.findViewById(R.id.linkMan_textView_phone);
                String phone = phoneNumber.getText().toString();

                Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phone));
                startActivity(intent);
            }
        });

        textViewBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @SuppressLint("HandlerLeak")
    private void initHandler() {
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case 1:
                        if (getFPhoneResponse.contains("10007")) {
                            Gson gsonFactory = new Gson();
                            FactoryBean factoryBean = gsonFactory.fromJson(getFPhoneResponse, FactoryBean.class);
                            listFactoryBeans = factoryBean.getContent();
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    for (int i = 0; i < listFactoryBeans.size(); i++) {
                                        String fId = listFactoryBeans.get(i).getFId();
                                        String fName = listFactoryBeans.get(i).getFName();
                                        String fManager = listFactoryBeans.get(i).getFManager();
                                        String fPhone = listFactoryBeans.get(i).getFPhone();


                                        HashMap<String, Object> hashMap = new HashMap<>();
                                        hashMap.put("fatherName", fName);
                                        hashMap.put("name", fManager);
                                        hashMap.put("phone", fPhone);
                                        hashMap.put("next", R.drawable.next1);
                                        hashMap.put("phoneIcon", R.drawable.icon_phone);

                                        listFactoryChar.add(hashMap);

                                        JSONObject jsonObject = new JSONObject();
                                        try {
                                            jsonObject.put("email", email);
                                            jsonObject.put("mode", 3);
                                            jsonObject.put("factory", fId);
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }

                                        new OceanUtil("getAccountAllInfo.php", jsonObject, new OceanUtil.HttpRequestCallback() {
                                            @Override
                                            public void callback(String strResponse) {
                                                Gson gson = new Gson();
                                                WorkshopBean workshopBean = gson.fromJson(strResponse, WorkshopBean.class);
                                                listWorkshopBeans.add(workshopBean.getContent());
                                            }
                                        }).AsynPostInfo();

                                    }

                                    Message message = new Message();
                                    message.what = 2;
                                    handler.sendMessage(message);
                                }
                            }).start();

                        }
                        if (getFPhoneResponse.contains("-20007")) {
                            Toast.makeText(LinkManActivity.this, "获取列表失败", Toast.LENGTH_SHORT).show();
                        }
                        break;

                    case 2:
                        for (int i = 0; i < listWorkshopBeans.size(); i++) {
                        for (int j = 0; j < listWorkshopBeans.get(i).size(); j++) {
                            String wName = listWorkshopBeans.get(i).get(j).getWName();
                            String wManager = listWorkshopBeans.get(i).get(j).getWManager();
                            String wPhone = listWorkshopBeans.get(i).get(j).getWPhone();
                            HashMap<String, Object> hashMap = new HashMap<>();
                            hashMap.put("fatherName", wName);
                            hashMap.put("name", wManager);
                            hashMap.put("phone", wPhone);
                            hashMap.put("next", R.drawable.next1);
                            hashMap.put("phoneIcon", R.drawable.icon_phone);
                            listFarmChar.add(hashMap);
                        }
                        simpleAdapter.notifyDataSetChanged();
                    }
                        qmuiTipDialog.dismiss();
                        break;
                }
            }
        };
    }

    void initView() {
        buttonFactoryChar = findViewById(R.id.linkMan_button_factoryChar);
        buttonFarmChar = findViewById(R.id.linkMan_button_farmChar);
        listViewLinkMan = findViewById(R.id.linkMan_listView_char);
        textViewBack = findViewById(R.id.text_linkman_back);

        SharedPreferences sharedPreferences = getSharedPreferences("account", MODE_PRIVATE);
        email = sharedPreferences.getString("email", "");

        buttonFactoryChar.setBackgroundResource(R.color.colorAccent);
        buttonFarmChar.setBackgroundResource(R.color.color_bg_grey);
        buttonFarmChar.setTextColor(Color.parseColor("#000000"));
        buttonFactoryChar.setTextColor(Color.parseColor("#ffffff"));
        listFactoryChar.clear();
        JSONObject getFactory = new JSONObject();
        try {
            getFactory.put("email", email);
            getFactory.put("mode", 2);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        qmuiTipDialog = new QMUITipDialog.Builder(this)
                .setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING)
                .setTipWord("正在加载")
                .create();
        qmuiTipDialog.show();

        new OceanUtil("getAccountAllInfo.php", getFactory, new OceanUtil.HttpRequestCallback() {
            @Override
            public void callback(String strResponse) {
                getFPhoneResponse = strResponse;
                Message message = new Message();
                message.what = 1;
                handler.sendMessage(message);
            }
        }).postInfo();
    }

    void initAdapter(ArrayList list) {
        simpleAdapter = new SimpleAdapter(LinkManActivity.this,
                list,
                R.layout.item_listview_linkman,
                new String[]{"fatherName", "name", "phone", "next", "phoneIcon"},
                new int[]{R.id.linkMan_textView_fatherName,
                        R.id.linkMan_textView_charName,
                        R.id.linkMan_textView_phone,
                        R.id.linkMan_imageView_next,
                        R.id.linkMan_imageView_phone});
        listViewLinkMan.setAdapter(simpleAdapter);
    }

    @Override
    protected void onStart() {
        super.onStart();
        buttonFactoryChar.performClick();
    }
}
